import FileSaver from 'file-saver'
import { loadFile as request } from '@/utils/request_web'
import JSZip from 'jszip'

function getFile(url) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      responseType: 'arraybuffer',
      method: 'get'
    }).then(data => {
      resolve(data.data)
    }).catch(error => {
      reject(error.toString())
    })
  })
}

export default function handleBatchDownload(fileList, zipName, completeFun) {
  const zip = new JSZip()
  const cache = {}
  const promises = []
  fileList.forEach(item => {
    const promise = getFile(item).then(data => { // 下载文件, 并存成ArrayBuffer对象
      const arr_name = item.split('/')
      const file_name = arr_name[arr_name.length - 1] // 获取文件名
      zip.file(file_name, data, { binary: true }) // 逐个添加文件
      cache[file_name] = data
    }).catch(e => {
      completeFun(false)
    })
    promises.push(promise)
  })
  Promise.all(promises).then(() => {
    zip.generateAsync({ type: 'blob' }).then(content => { // 生成二进制流
      FileSaver.saveAs(content, zipName + '.zip') // 利用file-saver保存文件
      completeFun(true)
    })
  })
}
